//图片地址
	var imgUrl = "http://www.ywkmhome.com/";
	var serverAddress = "http://192.168.6.188:8062/YWGL/";
	var userId=localStorage.userId;
	var weHead=localStorage.weHead;
	var autoUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx097fefed849b6ffd&redirect_uri=autourl&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
	var logoUrl='http://http://wechat.ywkmhome.com/YWGL/upload/logoImg.png';
(function(w){
	var ws=null
	w.back=function(hide){
	if(w.plus){
		ws||(ws=plus.webview.currentWebview());
		if(hide||ws.preate){
			ws.hide('auto');
		}else{
			ws.close('auto');
		}
	}else if(history.length>1){
		history.back();
	}else{
		w.close();
	}
	};
	
	w.closeWaiting=function(){
	waiting&&waiting.close();
	waiting=null;
	}
})(window);

//去空格
function trimStr(str){
	if(str == null || str == undefined) {
		return "";
	}
	if(typeof(str) == "boolean") {
		return str;
	}
	return str.replace(/(^\s*)|(\s*$)/g,"");
}


//ajax 错误处理方法
function ajaxError(xhr,type,errorThrown) {
	//type: "timeout", "error", "abort", "parsererror"
	console.log("异常处理==================================");
	console.log("xhr:" + xhr);
	console.log("type:" + type);
	if(type == "timeout") {
		mui.toast("连接超时");
	}else if(type == "abort") {
		mui.toast("连接服务器失败");
	}else if(type == "parsererror") {
		mui.toast("后台数据解析错误 ");
	}else {
		mui.toast("出现异常");
	}
}

//打开登录页面
function openLoginPage() {
	plus.webview.getLaunchWebview("index.html").show("pop-in",100);
	/*mui.openWindow({
	    url: '../index.html', 
	    id:'login'
	});*/
}

//动态加载js或css文件的方法
var dynamicLoading = {
    css: function(path){
		if(!path || path.length === 0){
			throw new Error('argument "path" is required !');
		}
		var head = document.getElementsByTagName('head')[0];
        var link = document.createElement('link');
        link.href = path;
        link.rel = 'stylesheet';
        link.type = 'text/css';
        head.appendChild(link);
    },
    js: function(path){
		if(!path || path.length === 0){
			throw new Error('argument "path" is required !');
		}
		var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.src = path;
        script.type = 'text/javascript';
        head.appendChild(script);
    }
}


function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate;
    return currentdate;
}

//时间戳转日期
function timestempToDate(nS) {     
    return new Date(parseInt(nS)).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ").substr(0,10);      
}

//时间戳转日期带时间
function timestempToDateTime(nS) {     
    return new Date(parseInt(nS)).toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ").substr(0,18);      
}

//时间格式转换
//2015/10/15 16:13:59   ---> 2015-10-15 16:13:59
function wfFormatDate(nS) { 
	if(nS == "" || nS == undefined) {
		return "";
	}else {
		console.log("nS:::" + nS);
		var res = nS.replace(new RegExp('/','gm'),"-");
		console.log("wfFormatDate:::" + res.substring(0,10));
	    return res;
	}
}
    
    
    
var serializeData = function(options) {
	if (options.processData && options.data && typeof options.data !== "string") {
		options.data = $.param(options.data, options.traditional);
	}
	if (options.data && (!options.type || options.type.toUpperCase() === 'GET')) {
		options.url = appendQuery(options.url, options.data);
		options.data = undefined;
	}
};
	
	
mui.plusReady(function(){
	(function($, window, undefined) {

		var jsonType = 'application/json';
		var htmlType = 'text/html';
		var rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
		var scriptTypeRE = /^(?:text|application)\/javascript/i;
		var xmlTypeRE = /^(?:text|application)\/xml/i;
		var blankRE = /^\s*$/;
	
		$.ajaxSettings = {
			type: 'GET',
			beforeSend: $.noop,
			success: $.noop,
			error: $.noop,
			complete: $.noop,
			context: null,
			xhr: function(protocol) {
				return new window.XMLHttpRequest();
			},
			accepts: {
				script: 'text/javascript, application/javascript, application/x-javascript',
				json: jsonType,
				xml: 'application/xml, text/xml',
				html: htmlType,
				text: 'text/plain'
			},
			timeout: 30000, //30s后连接超时
			processData: true,
			cache: true
		};
		var ajaxBeforeSend = function(xhr, settings) {
			var context = settings.context
			if (settings.beforeSend.call(context, xhr, settings) === false) {
				return false;
			}
		};
		var ajaxSuccess = function(data, xhr, settings) {
			settings.success.call(settings.context, data, 'success', xhr);
			ajaxComplete('success', xhr, settings);
			plus.nativeUI.closeWaiting();
		};
		// type: "timeout", "error", "abort", "parsererror"
		var ajaxError = function(error, type, xhr, settings) {
			settings.error.call(settings.context, xhr, type, error);
			ajaxComplete(type, xhr, settings);
			plus.nativeUI.closeWaiting();
		};
		// status: "success", "notmodified", "error", "timeout", "abort", "parsererror"
		var ajaxComplete = function(status, xhr, settings) {
			settings.complete.call(settings.context, xhr, status);
			plus.nativeUI.closeWaiting();
		};
	
		var serialize = function(params, obj, traditional, scope) {
			var type, array = $.isArray(obj),
				hash = $.isPlainObject(obj);
			$.each(obj, function(key, value) {
				type = $.type(value);
				if (scope) {
					key = traditional ? scope :
						scope + '[' + (hash || type === 'object' || type === 'array' ? key : '') + ']';
				}
				// handle data in serializeArray() format
				if (!scope && array) {
					params.add(value.name, value.value);
				}
				// recurse into nested objects
				else if (type === "array" || (!traditional && type === "object")) {
					serialize(params, value, traditional, key);
				} else {
					params.add(key, value);
				}
			});
		};
		var serializeData = function(options) {
			
			if (options.processData && options.data && typeof options.data !== "string") {
				options.data = $.param(options.data, options.traditional);
			}
			if (options.data && (!options.type || options.type.toUpperCase() === 'GET')) {
				options.url = appendQuery(options.url, options.data);
				options.data = undefined;
			}
		};
		var appendQuery = function(url, query) {
			if (query === '') {
				return url;
			}
			return (url + '&' + query).replace(/[&?]{1,2}/, '?');
		};
		var mimeToDataType = function(mime) {
			if (mime) {
				mime = mime.split(';', 2)[0];
			}
			return mime && (mime === htmlType ? 'html' :
				mime === jsonType ? 'json' :
				scriptTypeRE.test(mime) ? 'script' :
				xmlTypeRE.test(mime) && 'xml') || 'text';
		};
		var parseArguments = function(url, data, success, dataType) {
			if ($.isFunction(data)) {
				dataType = success, success = data, data = undefined;
			}
			if (!$.isFunction(success)) {
				dataType = success, success = undefined;
			}
			return {
				url: url,
				data: data,
				success: success,
				dataType: dataType
			};
		};
		$.ajax = function(url, options) {
			if (typeof url === "object") {
				options = url;
				url = undefined;
			}
			var settings = options || {};
			settings.url = url || settings.url;
			for (var key in $.ajaxSettings) {
				if (settings[key] === undefined) {
					settings[key] = $.ajaxSettings[key];
				}
			}
			serializeData(settings);
			var dataType = settings.dataType;
	
			if (settings.cache === false || ((!options || options.cache !== true) && ('script' === dataType))) {
				settings.url = appendQuery(settings.url, '_=' + $.now());
			}
			var mime = settings.accepts[dataType];
			var headers = {};
			var setHeader = function(name, value) {
				headers[name.toLowerCase()] = [name, value];
			};
			var protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol;
			var xhr = settings.xhr(settings);
			var nativeSetHeader = xhr.setRequestHeader;
			var abortTimeout;
	
			setHeader('X-Requested-With', 'XMLHttpRequest');
			setHeader('Accept', mime || '*/*');
			if (!!(mime = settings.mimeType || mime)) {
				if (mime.indexOf(',') > -1) {
					mime = mime.split(',', 2)[0];
				}
				xhr.overrideMimeType && xhr.overrideMimeType(mime);
			}
			if (settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() !== 'GET')) {
				setHeader('Content-Type', settings.contentType || 'application/x-www-form-urlencoded');
			}
			if (settings.headers) {
				for (var name in settings.headers)
					setHeader(name, settings.headers[name]);
			}
			xhr.setRequestHeader = setHeader;
	
			xhr.onreadystatechange = function() {
				if (xhr.readyState === 4) {
					xhr.onreadystatechange = $.noop;
					clearTimeout(abortTimeout);
					var result, error = false;
					if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304 || (xhr.status === 0 && protocol === 'file:')) {
						dataType = dataType || mimeToDataType(settings.mimeType || xhr.getResponseHeader('content-type'));
						result = xhr.responseText;
						try {
							// http://perfectionkills.com/global-eval-what-are-the-options/
							if (dataType === 'script') {
								(1, eval)(result);
							} else if (dataType === 'xml') {
								result = xhr.responseXML;
							} else if (dataType === 'json') {
								result = blankRE.test(result) ? null : $.parseJSON(result);
							}
						} catch (e) {
							error = e;
						}
	
						if (error) {
							ajaxError(error, 'parsererror', xhr, settings);
						} else {
							ajaxSuccess(result, xhr, settings);
						}
					} else {
						ajaxError(xhr.statusText || null, xhr.status ? 'error' : 'abort', xhr, settings);
					}
				}
			};
			if (ajaxBeforeSend(xhr, settings) === false) {
				xhr.abort();
				ajaxError(null, 'abort', xhr, settings);
				return xhr;
			}
	
			if (settings.xhrFields) {
				for (var name in settings.xhrFields) {
					xhr[name] = settings.xhrFields[name];
				}
			}
			plus.nativeUI.showWaiting("请稍等...");
			var async = 'async' in settings ? settings.async : true;
			xhr.open(settings.type.toUpperCase(), settings.url, async, settings.username, settings.password);
	
			for (var name in headers) {
				nativeSetHeader.apply(xhr, headers[name]);
			}
			if (settings.timeout > 0) {
				abortTimeout = setTimeout(function() {
					xhr.onreadystatechange = $.noop;
					xhr.abort();
					ajaxError(null, 'timeout', xhr, settings);
				}, settings.timeout);
			}
			xhr.send(settings.data ? settings.data : null);
			
			//plus.nativeUI.closeWaiting();
			return xhr;
		};
	
	
		$.param = function(obj, traditional) {
			var params = [];
			params.add = function(k, v) {
				this.push(encodeURIComponent(k) + '=' + encodeURIComponent(v));
			};
			serialize(params, obj, traditional);
			return params.join('&').replace(/%20/g, '+');
		};
		$.get = function( /* url, data, success, dataType */ ) {
			return $.ajax(parseArguments.apply(null, arguments));
		};
	
		$.post = function( /* url, data, success, dataType */ ) {
			var options = parseArguments.apply(null, arguments);
			options.type = 'POST';
			return $.ajax(options);
		};
	
		$.getJSON = function( /* url, data, success */ ) {
			var options = parseArguments.apply(null, arguments);
			options.dataType = 'json';
			return $.ajax(options);
		};
	
		$.fn.load = function(url, data, success) {
			if (!this.length)
				return this;
			var self = this,
				parts = url.split(/\s/),
				selector,
				options = parseArguments(url, data, success),
				callback = options.success;
			if (parts.length > 1)
				options.url = parts[0], selector = parts[1];
			options.success = function(response) {
				if (selector) {
					var div = document.createElement('div');
					div.innerHTML = response.replace(rscript, "");
					var selectorDiv = document.createElement('div');
					var childs = div.querySelectorAll(selector);
					if (childs && childs.length > 0) {
						for (var i = 0, len = childs.length; i < len; i++) {
							selectorDiv.appendChild(childs[i]);
						}
					}
					self[0].innerHTML = selectorDiv.innerHTML;
				} else {
					self[0].innerHTML = response;
				}
				callback && callback.apply(self, arguments);
			};
			$.ajax(options);
			
			return this;
		};
	
	})(mui, window);

});


/**
 * 金额小写转大写
 * @param num
 * @returns {String}
 */
function NoToChinese(num) {
	if (!/^\d*(\.\d*)?$/.test(num)) {
		alert("Number is wrong!");
		return "Number is wrong!";
	}
	var AA = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖");
	var BB = new Array("", "拾", "佰", "仟", "萬", "億", "点", "");
	var a = ("" + num).replace(/(^0*)/g, "").split("."), k = 0, re = "";
	for ( var i = a[0].length - 1; i >= 0; i--) {
		switch (k) {
		case 0:
			re = BB[7] + re;
			break;
		case 4:
			if (!new RegExp("0{4}\\d{" + (a[0].length - i - 1) + "}$")
					.test(a[0]))
				re = BB[4] + re;
			break;
		case 8:
			re = BB[5] + re;
			BB[7] = BB[5];
			k = 0;
			break;
		}
		if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0)
			re = AA[0] + re;
		if (a[0].charAt(i) != 0)
			re = AA[a[0].charAt(i)] + BB[k % 4] + re;
		k++;
	}

	if (a.length > 1) //加上小数部分(如果有小数部分) 
	{
		re += BB[6];
		for ( var i = 0; i < a[1].length; i++)
			re += AA[a[1].charAt(i)];
	}
	if (re.substring((re.length - 3), re.length) == "点零零") {
		re = re.substring(0, re.length - 3) + "元整";
	} else if (re.substring((re.length - 3), (re.length - 1)) == "点零")
		re = re.substring(0, (re.length - 3)) + "元零"
				+ re.substring(re.length - 1, re.length) + "分";
	else {
		if(re.substring((re.length-1),re.length)=="零")
			re = re.substring(0, (re.length - 3)) + "元"
			+ re.substring(re.length - 2, re.length - 1) + "角";
		else
		re = re.substring(0, (re.length - 3)) + "元"
				+ re.substring(re.length - 2, re.length - 1) + "角"
				+ re.substring(re.length - 1, re.length) + "分";
	}
	if(re.substring(0, 1)=="元"){
		re="零"+re;
	}
	return re;
}

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

//是否存在指定函数 
function isExitsFunction(funcName) {
    try {
        if (typeof(eval(funcName)) == "function") {
            return true;
        }
    } catch(e) {}
    return false;
}


//表单日期校验
function disablesub(beginTime,endTime){
	console.log(beginTime + "|" + endTime);
	
	if(beginTime == "" || endTime == "") {
		return 0;
	}
     var bngDate = new Date(beginTime.substr(0,4),beginTime.substr(5,2)-1,beginTime.substr(8,2));
     var endDate = new Date(endTime.substr(0,4),endTime.substr(5,2)-1,endTime.substr(8,2));
     var days = (endDate.getTime()-bngDate.getTime())/24/60/60/1000;
     var total=parseInt(days)+1;
     if(total<1){
    	 total=0;
    	 mui.toast("结束日期不能比起始日期小");
     }
    return total;
};

function openBrowser(filePath) {
	var url = serverFileDownLoad + filePath;
	var btnArray = ['下载','取消'];
  	mui.confirm('确认下载文件吗？','提示',btnArray,function(e){
  		if(e.index==0){
  			plus.runtime.openURL( url );
  		}
  	});
}

function openBrowserUrl(url) {
	var btnArray = ['下载','取消'];
  	mui.confirm('确认下载文件吗？','提示',btnArray,function(e){
  		if(e.index==0){
  			plus.runtime.openURL( url );
  		}
  	});
}

//在指定节点插入新节点
function insertAfter(newEl, targetEl) {
    var parentEl = targetEl.parentNode;
            
     if(parentEl.lastChild == targetEl)
     {
           parentEl.appendChild(newEl);
      }else
      {
           parentEl.insertBefore(newEl,targetEl.nextSibling);
       }            
}

//获取表单数据
function getFormData(formId){
	var paramArray = {};
	var form = document.getElementById(formId);
	//获取input元素
	var inputElements =  form.getElementsByTagName('input');
	//获取textare元素
	var textareas =  form.getElementsByTagName('textarea');
	//获取input元素的值
	for ( var i = 0 ; i < inputElements.length ; i++){ 
		switch(inputElements[i].type.toLowerCase()){
			case 'hidden':
			case 'password':
			case 'text':
			case 'submit':
				paramArray[inputElements[i].name]=inputElements[i].value;
				break;
			case 'checkbox':
			case 'radio':
				if(inputElements[i].checked){
					paramArray[inputElements[i].name]=inputElements[i].value;
				}
				break;
		}
	}
	//获取textarea的值
	for ( var i = 0 ; i < textareas.length ; i++){
		paramArray[textareas[i].name]=textareas[i].value;
	}
	return paramArray;
}
/*
//无参数请求接口
function actionNoParam(url,tag){
	var param={};
	mui.getJSONP(serverAddress+url,
   			{data:JSON.stringify(tag)},
            function(data) { 
		         console.log(data); 
		         param=data
		});
	return param;
}*/

function checkUserInfo(tag){
	if(tag==undefined||tag==""||tag=="undefined"){
		mui.alert("获取用户信息失败，请退出重新加载");
		return true;
	}else{
		return false;
	}
}

function neterror(tag){
	if(tag==undefined||tag==""||tag=="undefined"){
		mui.alert("请求服务器异常，请稍后再试");
		return true;
	}else{
		return false;
	}
}

